package xor.droid.nav;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

public class GLModel {

	private float vertices[] = {
			// triangle 24bytes (6x4)
			0f, 1f, // p0
			1f, -1f, // p1
			-1f, -1f // p2
	};

	private float rgbaVals[] = {
			// red, green, blue, alpha
			1, 1, 0, .5f, .25f, 0, .85f, 1, 0, 1, 1, 1 };

	private FloatBuffer vertBuff, colorBuff;

	private short[] pIndex = { 0, 1, 2 };

	private ShortBuffer pBuff;

	public GLModel() {
		ByteBuffer bBuff = ByteBuffer.allocateDirect(vertices.length * 4);
		bBuff.order(ByteOrder.nativeOrder());
		vertBuff = bBuff.asFloatBuffer();
		vertBuff.put(vertices);
		vertBuff.position(0);

		// shorts -> 2
		ByteBuffer pbBuff = ByteBuffer.allocateDirect(pIndex.length * 2);
		pbBuff.order(ByteOrder.nativeOrder());
		pBuff = pbBuff.asShortBuffer();
		pBuff.put(pIndex);
		pBuff.position(0);

		// color
		ByteBuffer cBuff = ByteBuffer.allocateDirect(rgbaVals.length * 4);
		cBuff.order(ByteOrder.nativeOrder());
		colorBuff = cBuff.asFloatBuffer();
		colorBuff.put(rgbaVals);
		colorBuff.position(0);

	}

	public void draw(GL10 gl) {
		// Connect points clockwise
		gl.glFrontFace(GL10.GL_CW);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
		// Stride to skip something (0f, 1f, B ) <- skip b
		gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertBuff);
		// 4 dims -> rgbA
		gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuff);
		gl.glDrawElements(GL10.GL_TRIANGLES, pIndex.length,
				GL10.GL_UNSIGNED_SHORT, pBuff);

		gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);

	}
}
